import urllib.request as ur
import lxml.etree as le
import re
import random
import time
import code
import user_agent
from selenium import webdriver
# cookie = ''
class Daliip():
    def __init__(self):
        self.ipp_s = []
        self.host_s = []
        self.ip_s = []
        self.data_s = []
        self.cookie_str = ''
        self.driver = None
        self.driver_cookies = ''
    def set_dali_ip(self):
        self.driver = webdriver.Chrome(
                    executable_path='D:\Google\Chrome\Application\chromedriver.exe',
                )
        self.driver.get('https://www.freeip.top/')
        self.driver_cookies = self.driver.get_cookies()
        # print(driver_cookies)

        for driver_cookie in self.driver_cookies:
             name = driver_cookie['name']
             value = driver_cookie['value']
             self.cookie_str+=f'{name}={value}; '
        if self.cookie_str:
                request = ur.Request(
                    url='https://www.freeip.top/',
                    headers={
                        'User-Agent':user_agent.get_user_agent_pc(),
                        'Cookie':self.cookie_str
                    }
                )
                # time.sleep(0.1)
                response = ur.urlopen(request).read()
                # print(response)

        # # print(str(response))
                html_x =le.HTML(response)
        # # # print(html_x)
                self.ip_s+=html_x.xpath("//tbody//td[1]//text()")
                self.host_s+=html_x.xpath("//tbody//td[2]//text()")
                # print(ip_s)
        for i in self.ip_s:
            self.data_s.append(
                {
                    'ip':i,
                }
            )
        # print(ip_s)
        for i in range(len(self.host_s)):
            self.data_s[i]['host'] = self.host_s[i]
        # print(data_s)
        for data in self.data_s:
            self.ipp_s.append(f'{data["ip"]}:{data["host"]}')
    def get_daili_ip(self):
        if self.ipp_s:
            # print('ipps',self.ipp_s)
            self.driver.quit()
            return self.ipp_s
        else:
            # print('11')
            self.set_dali_ip()
            return self.get_daili_ip()

if __name__ == '__main__':
    Daliip().get_daili_ip()

# print(get_daili_ip())